package com.kabuda.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kabuda.blog.dao.dos.Archives;
import com.kabuda.blog.dao.mapper.ArticleBodyMapper;
import com.kabuda.blog.dao.mapper.ArticleMapper;
import com.kabuda.blog.dao.mapper.ArticleTagMapper;
import com.kabuda.blog.dao.pojo.Article;
import com.kabuda.blog.dao.pojo.ArticleBody;
import com.kabuda.blog.dao.pojo.ArticleTag;
import com.kabuda.blog.dao.pojo.SysUser;
import com.kabuda.blog.service.*;
import com.kabuda.blog.utils.UserThreadLocal;
import com.kabuda.blog.vo.ArticleVo;
import com.kabuda.blog.vo.Result;
import com.kabuda.blog.vo.TagVo;
import com.kabuda.blog.vo.params.ArticleParam;
import com.kabuda.blog.vo.params.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kabuda
 * @create 2023-01-16 14:58
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TagService tagService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    private ArticleBodyService articleBodyService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    /**
     * 主页 文章列表
     *
     * @param pageParams
     * @return
     */

    @Override
    public Result listArticles(PageParams pageParams) {
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage= this.articleMapper.listArticles(page, pageParams.getCategoryId(), pageParams.getTagId(),pageParams.getYear(),pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return Result.success(copyList(records,true,true));
    }
    //@Override
    //public Result listArticles(PageParams pageParams) {
    //    Page<Article> page = new Page<>(pageParams.getPage(),pageParams.getPageSize());
    //    LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
    //    if(pageParams.getCategoryId()!= null){
    //        queryWrapper.eq(Article::getCategoryId,pageParams.getCategoryId());
    //    }
    //    if(pageParams.getTagId()!= null){
    //        LambdaQueryWrapper<ArticleTag> TagQueryWrapper = new LambdaQueryWrapper<>();
    //        TagQueryWrapper.eq(ArticleTag::getTagId,pageParams.getTagId());
    //        TagQueryWrapper.select(ArticleTag::getArticleId);
    //        List<ArticleTag> articleTags = articleTagMapper.selectList(TagQueryWrapper);
    //        ArrayList<Long> ids = new ArrayList<>();
    //        for (ArticleTag articleTag : articleTags) {
    //            ids.add(articleTag.getArticleId());
    //        }
    //        if(ids.size() > 0){
    //            queryWrapper.in(Article::getId,ids);
    //        }
    //    }
    //    //置顶排序（业务逻辑1为置顶，0为不）
    //    queryWrapper.orderByDesc(Article::getWeight);
    //    //时间排序
    //    queryWrapper.orderByDesc(Article::getCreateDate);
    //    Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
    //    List<Article> records = articlePage.getRecords();
    //    //我们定义一个vo返回，List<Article>---》List<ArticleVo>
    //    List<ArticleVo> articleVos = copyList(records,true,true);
    //    return Result.success(articleVos);
    //}

    /**
     * 主页 热点文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result hotsArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getViewCounts);
        queryWrapper.select(Article::getId, Article::getTitle);
        //注意limit后有空格
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));

    }

    /**
     * 主页 最新文章
     *
     * @param limit
     * @return
     */
    @Override
    public Result newArticles(int limit) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Article::getCreateDate);
        queryWrapper.select(Article::getId, Article::getTitle);
        //注意limit后有空格
        queryWrapper.last("limit " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        return Result.success(copyList(articles, false, false));
    }

    /**
     * 文章归档
     *
     * @return
     */
    @Override
    public Result listArchives() {
        List<Archives> archives = articleMapper.listArchives();
        return Result.success(archives);
    }

    @Autowired
    private ThreadService threadService;

    /**
     * 根据id查找文章信息
     *
     * @param id
     * @return
     */
    @Override
    public Result findArticleById(Long id) {
        //获得基本的文章信息
        Article article = articleMapper.selectById(id);
        ArticleVo articleVo = copy(article, true, true, true, true);
        //更新阅读量
        threadService.UpdateViewCount(articleMapper, article);
        return Result.success(articleVo);
    }

    /**
     * List<Article>转为List<ArticleVo>
     *
     * @param records
     * @param isTags
     * @param isAuthor
     * @return
     */
    private List<ArticleVo> copyList(List<Article> records, boolean isTags, boolean isAuthor) {
        ArrayList<ArticleVo> list = new ArrayList<>();
        for (Article record : records) {
            ArticleVo copy = copy(record, isTags, isAuthor, false, false);
            list.add(copy);
        }
        return list;
    }

    private List<ArticleVo> copyList(List<Article> records, boolean isTags, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArrayList<ArticleVo> list = new ArrayList<>();
        for (Article record : records) {
            ArticleVo copy = copy(record, isTags, isAuthor, isBody, isCategory);
            list.add(copy);
        }
        return list;
    }

    /**
     * Article转为ArticleVo
     *
     * @param article
     * @param isTag
     * @param isAuthor
     * @return
     */
    private ArticleVo copy(Article article, boolean isTag, boolean isAuthor, boolean isBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-mm-dd HH:mm:ss"));

        if (isTag) {
            articleVo.setTags(tagService.getTagByArticleId(article.getId()));
        }
        if (isAuthor) {
            articleVo.setAuthor(sysUserService.getUserById(article.getAuthorId()).getNickname());
        }
        if (isBody) {
            articleVo.setBody(articleBodyService.getArticleBodyByArticleId(article.getId()));
        }
        if (isCategory) {
            articleVo.setCategory(categoryService.getCategoryById(article.getCategoryId()));
        }

        return articleVo;
    }

    @Override
    @Transactional
    public Result publish(ArticleParam articleParam) {
        SysUser sysUser = UserThreadLocal.get();

        Article article = new Article();
        article.setAuthorId(sysUser.getId());
        article.setCategoryId(articleParam.getCategory().getId());
        article.setCreateDate(System.currentTimeMillis());
        article.setCommentCounts(0);
        article.setSummary(articleParam.getSummary());
        article.setTitle(articleParam.getTitle());
        article.setViewCounts(0);
        article.setWeight(Article.Article_Common);
        article.setBodyId(-1L);
        this.articleMapper.insert(article);

        //tags
        List<TagVo> tags = articleParam.getTags();
        if (tags != null) {
            for (TagVo tag : tags) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(tag.getId());
                this.articleTagMapper.insert(articleTag);
            }
        }
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);

        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(article.getId());
        return Result.success(articleVo);
    }

    @Override
    public Result search(String searchString) {
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Article::getTitle,searchString);
        List<Article> articles = articleMapper.selectList(wrapper);
        return Result.success(copyList(articles,false,false));
    }


}
